package com.cloud.sso.oauth.service;

import com.cloud.sso.common.constant.UserState;
import com.cloud.sso.common.log.factory.LogTaskFactory;
import com.cloud.sso.entity.User;
import com.cloud.sso.common.exception.AppException;
import com.cloud.sso.mapper.UserMapper;
import com.cloud.sso.oauth.obj.AppUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class AppUserDetailService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {

        if (userName == null) {
            return null;
        }

        // 用户认证
        User user = userMapper.getByUserName(userName);

        if (StringUtils.isEmpty(userName)) {
            throw new AppException("用户名不能为空");
        }
        if (user.getState() == UserState.DISABLE) {
            throw new AppException("该用户已被禁用");
        }
        if (user != null) {
            AppUserDetails appUserDetails = new AppUserDetails(user.getId(), user.getUserName(), user.getPassword(),
                    user.getRealName(), user.getTelephone(), user.getEmail(), user.getSysManage());
            appUserDetails.setAuthorities(new ArrayList<>());

            userMapper.updateLoginTime(user.getId());

            return appUserDetails;
        } else {
            throw new AppException("该用户不存在");
        }

    }


    public Collection<GrantedAuthority> convertRoleToGrantedAuthority(Set<String> userRoleCodes) {
        if (userRoleCodes == null) {
            return new HashSet<GrantedAuthority>();
        } else {
            Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
            userRoleCodes.stream().filter((role) -> {
                return !StringUtils.isEmpty(role);
            }).forEach((role) -> {
                role = role.trim();
                if (!role.startsWith("ROLE_")) {
                    role = "ROLE_" + role;
                }

                grantedAuthorities.add(new SimpleGrantedAuthority(role));
            });
            return grantedAuthorities;
        }
    }

    public AppUserDetails getCurrentUserDetails() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        return (AppUserDetails) authentication.getPrincipal();
    }
}
